import os
import sys
import shutil

from datetime import datetime

def list_and_download(server_path, local_path, file_name_start,file_name_end, jiancheng):

    # 获取源目录中所有word文件的路径和修改时间
    remotefiles = []
    for dirpath, childdir, filenames in os.walk(server_path):
        for filename in filenames:
            if filename.startswith(file_name_start) and filename.endswith(file_name_end):
                full_path = os.path.join(dirpath, filename)
                remotefiles.append((full_path, os.path.getmtime(full_path)))

    # 获得最新的文件到变更时间
    if not remotefiles:
        print('没有合适的文档')
        return
    else:
        # 根据修改时间对文件进行排序
        remotedoc = sorted(remotefiles, key=lambda x: x[1], reverse=True)
        latest_remotefile = remotedoc[0][0]
        latest_remotefile_mtime = remotedoc[0][1]
        #找出本地文件的最新时间
        localdocfiles = [
            (os.path.join(local_path, filename), os.path.getmtime(os.path.join(local_path, filename)))
            for filename in os.listdir(local_path)
            if filename.startswith(file_name_start) and filename.endswith(file_name_end)
        ]
        localdoc = sorted(localdocfiles, key=lambda x: x[1], reverse=True)
        localfilename = os.path.join(local_path, os.path.basename(latest_remotefile))

        # 如果服务器文件时间比本地新，复制最新的文件到本机目录
        if localdoc:
            latest_localfile_mtime = localdoc[0][1]
            if latest_remotefile_mtime > latest_localfile_mtime:
                print('现在复制', latest_remotefile, '...')
                shutil.copy2(latest_remotefile, localfilename)
                print(os.path.basename(latest_remotefile), '已成功复制')
            else:
                print(jiancheng,' 文件没有更新')
                return
        else:
            print('现在复制', latest_remotefile, '...')
            shutil.copy2(latest_remotefile, localfilename)
            print(os.path.basename(latest_remotefile), '已成功复制')


if __name__ == '__main__':
    # 定义服务器共享文件夹路径
    # server_path = "\\\\10.80.3.151\\气象服务\\预报服务\\2025"
    server_path = "\\\\192.168.110.109\\hxq"
    #定义本地存放目录
    local_path1 = "e:\\hxq"
    local_path2 = "e:\\hxq"
    local_path3 = "e:\\hxq"
    local_path4 = "e:\\hxq"
    local_path5 = "e:\\hxq"
    local_path6 = "e:\\hxq"
    local_path7 = "e:\\hxq"
    local_path8= "e:\\hxq"
    #定义所需要的文件名的开头和结尾，以及本地存放位置，形式为：根据需要修改（名称开头，名称结尾，文件简称，本地储存目录）
    needfiles = [
        ('德州市2025年', '短期气候预测.doc', '短期气候预测', local_path1),
        ('山东省分县月降水量短期气候趋势预测结果.TXT', '', '月降水量', local_path2),
        ('山东省分县月平均气温短期气候趋势预测结果.TXT', '', '月平均气温', local_path3),
        ('重要气象信息专报（天气实况）', '.doc', '天气实况', local_path4),
        ('2025年', '旬天气趋势预报.doc','旬天气预报', local_path5),
        ('重要气象信息专报（三夏预报）', '.doc', '三夏预报', local_path6),
        ('重要气象信息专报（预测预报）', '.doc', '预测预报', local_path7),
        ('春运气象服务', '.doc', '春运气象服务', local_path8),

        ('重要气象信息', '.docx', '测试1', local_path1),
        ('hh', '.txt', '测试2', local_path1)
    ]
    # 检查路径是否存在
    if os.path.exists(server_path):
        print(server_path, "连接成功！", datetime.now())

        for file in needfiles:
            list_and_download(server_path,file[-1],file[0],file[1],file[2])

    else:
        print("连接失败，请检查")
        sys.exit(1)

